package com.lb.shopguide.ui.fragment.guide;

import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterHomeInfo;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.UpdateInfoBean;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.entity.home.HomeMijiBean;
import com.lb.shopguide.entity.home.HomeMsgBean;
import com.lb.shopguide.entity.home.HomeOrderRobBean;
import com.lb.shopguide.entity.home.HomeOrderUpdateBean;
import com.lb.shopguide.entity.home.HomeRecommendBean;
import com.lb.shopguide.event.guide.ChangeStaffEvent;
import com.lb.shopguide.event.guide.GuideDivideUpdateEvent;
import com.lb.shopguide.event.guide.HomeMijiEvent;
import com.lb.shopguide.event.guide.HomeOrderRefreshEvent;
import com.lb.shopguide.event.guide.HomeRecommendEvent;
import com.lb.shopguide.event.guide.MessageReadEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.event.guide.UserBeanEvent;
import com.lb.shopguide.event.guide.UserInfoChangeEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.im.session.SessionHelper;
import com.lb.shopguide.manager.service.update.UpdateManager;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.activity.MessageDetailActivity;
import com.lb.shopguide.ui.dialog.DialogShowBarcode;
import com.lb.shopguide.ui.fragment.guide.goods.FragmentSelectGoods;
import com.lb.shopguide.ui.fragment.guide.miji.FragmentMijiDetail;
import com.lb.shopguide.ui.fragment.guide.order.FragmentCheckout;
import com.lb.shopguide.ui.fragment.guide.order.FragmentOrderDetail;
import com.lb.shopguide.ui.fragment.guide.order.FragmentOrderManager;
import com.lb.shopguide.ui.fragment.guide.order.FragmentSureOrder;
import com.lb.shopguide.ui.view.AppBarStateChangeListener;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/5/29.
 */

public class FragmentHome extends BaseMainFragment {
    @BindView(R.id.app_bar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.layout_logos)
    LinearLayout layoutLogos;
    @BindView(R.id.layout_logos_toolbar)
    LinearLayout layoutLogoToolbar;
    @BindView(R.id.layout_top)
    RelativeLayout layoutTop;
    @BindView(R.id.layout_top_content)
    RelativeLayout layoutTopContent;
    @BindView(R.id.layout_quick_pay)
    LinearLayout layoutQuickPay;
    @BindView(R.id.iv_guider)
    ImageView ivGuider;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_month_sale)
    TextView tvMonthSale;
    @BindView(R.id.tv_guider_name)
    TextView tvGuiderName;
    @BindView(R.id.iv_barcode)
    ImageView ivBarcode;
    @BindView(R.id.tv_scanner)
    TextView tvScanner;
    @BindView(R.id.tv_product)
    TextView tvProduct;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_activity)
    TextView tvActivity;
    @BindView(R.id.tv_level_name)
    TextView tvLevelName;
    @BindView(R.id.iv_scanner)
    ImageView ivScanner;
    @BindView(R.id.iv_product)
    ImageView ivProduct;
    @BindView(R.id.iv_order)
    ImageView ivOrder;
    @BindView(R.id.iv_activity)
    ImageView ivActivity;
    @BindView(R.id.iv_wave)
    ImageView ivWave;
    @BindView(R.id.iv_bottom_line)
    View ivLine;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    public View noDataView;
    public View errorView;

    private AppBarStateChangeListener mAppBarStateChangeListener;
    private AppBarStateChangeListener.State curState;

    private UserBean userBean;
    private List<MultiItemEntity> mHomeInfoList;
    private AdapterHomeInfo mAdapterHomeInfo;
    private List<RecentContact> mRecentContacts;


    private int[] mTopPoint = new int[2], mLayoutLogosPoint = new int[2];

    public static FragmentHome newInstance() {
        return new FragmentHome();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_guide_home;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mHomeInfoList = new ArrayList<>();
        initRequest();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_home, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有消息");

        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
//        setUpToolbar();

        mAppBarStateChangeListener = new AppBarStateChangeListener() {

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                curState = state;
                LogUtils.d("onStateChanged============" + state);
            }

            @Override
            public void onOffsetChanged(State state, float offset) {
                translationView(offset);
            }
        };
        mAppBarLayout.addOnOffsetChangedListener(mAppBarStateChangeListener);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterHomeInfo = new AdapterHomeInfo(mHomeInfoList);
        mRecyclerView.setAdapter(mAdapterHomeInfo);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).paintProvider(mAdapterHomeInfo).build());

        initListener();

        checkToolbarIfClick();
        setUpRecyclerView();

//        ToastUtils.showShort("this is hot fixed");
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentHome.class.getName();
    }

    private void bindData() {
        ((GuideMainActivity) _mActivity).setUserBean(userBean);
        EventBus.getDefault().post(new UserBeanEvent(userBean));
        ImageLoaderUtils.displayCircle(mContext, ivGuider, userBean.getStaffHeadPicUrl());
        if (userBean.getStaffType() == AppConstant.STAFF_TYPE_MANAGER) {
            tvLevelName.setText("店长");
        } else if (userBean.getStaffType() == AppConstant.STAFF_TYPE_GUIDE) {
            tvLevelName.setText("超级导购");
        }
        tvGuiderName.setText(userBean.getStaffNickName());
        tvShopName.setText(userBean.getStoreName());
        tvMonthSale.setText("￥" + userBean.getMonthlySales() + "/本月");
        if (!TextUtils.isEmpty(mUserConfigManager.getMijiInfo())) {
            bindMiji(mUserConfigManager.getMijiInfo());
        }
        UpdateInfoBean updateInfoBean = ((GuideMainActivity) _mActivity).getUpdateInfoBean();
        if (updateInfoBean != null && BizUtil.compareVersion(updateInfoBean.getAppVersion(), AppUtils.getAppVersionName())) {//
            mHomeInfoList.add(updateInfoBean);
        }
    }

    private void initRequest() {
        getStaffInfo();
        getHomeMsgInfo();
        getRecentContact();
    }

    private void getStaffInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    userBean = (UserBean) JsonUtil.getObject(response.getReturnContent(), UserBean.class);
                    bindData();
                }
            }
        };
        ApiMethodGuide.getStaffInfo(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestOperateMsg(int msgItemTypeCode, String appMsgCode, final String orderNum) {
        HashMap hashMap = new HashMap();
        hashMap.put("msgItemTypeCode", msgItemTypeCode);
        hashMap.put("appMsgCode", appMsgCode);
        hashMap.put("staffCode", mUserConfigManager.getUserId());
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    EventBus.getDefault().post(new StartBrotherEvent(FragmentOrderDetail.newInstance(orderNum, AppConstant.FROM_MAIN_ACTIVITY)));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.operateOrder(new SimpleLbObserver(listener, otherListener), body, this, FragmentEvent.DESTROY_VIEW);
    }



    private void initListener() {
        mAdapterHomeInfo.setOnOrderClickListener(new AdapterHomeInfo.OnOrderClickListener() {
            @Override
            public void onOrderClick(HomeOrderUpdateBean bean) {
                mHomeInfoList.remove(bean);
                refreshRecyclerView();
                sendRequestOperateMsg(bean.getMsgItemTypeCode(), bean.getAppMsgCode(), bean.getOrderNum());
            }
        });
        mAdapterHomeInfo.setOnRobOrderListener(new AdapterHomeInfo.OnRobOrderListener() {
            @Override
            public void onRobOrder(HomeOrderRobBean bean) {
                mHomeInfoList.remove(bean);
                refreshRecyclerView();
                sendRequestOperateMsg(bean.getMsgItemTypeCode(), bean.getAppMsgCode(), bean.getOrderNum());

            }
        });
        mAdapterHomeInfo.setOnMessageClickListener(new AdapterHomeInfo.OnMessageClickListener() {
            @Override
            public void onMessageClick(HomeMsgBean msgBean) {
                MessageDetailActivity.start(mContext, msgBean.getAccount(), SessionHelper.getP2pCustomization(msgBean.getAccount()), null);
                mHomeInfoList.remove(msgBean);
                refreshRecyclerView();
            }
        });
        mAdapterHomeInfo.setOnMijiClickListener(new AdapterHomeInfo.OnMijiClickListener() {
            @Override
            public void onMijiClick(HomeMijiBean mijiBean) {
                String url;
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    url = "https://singlepage.storeer.com/v2/esotericaInfo?esoCode=" + mijiBean.getEsoCode() + "&token=" + mUserConfigManager.getUserToken();
                } else {
                    url = "http://192.168.1.102:8088/v2/esotericaInfo?esoCode=" + mijiBean.getEsoCode() + "&token=" + mUserConfigManager.getUserToken();
                }
                EventBus.getDefault().post(new StartBrotherEvent(FragmentMijiDetail.newInstance(url, mijiBean.getEsoCode(), mijiBean.getEsoTitle())));
            }
        });
        mAdapterHomeInfo.setOnSystemUpdateClickListener(new AdapterHomeInfo.OnSystemUpdateClickListener() {
            @Override
            public void onUpdateClick(UpdateInfoBean updateInfoBean) {
                UpdateManager updateManager = new UpdateManager(mContext);
                updateManager.showUpdateInfo(updateInfoBean, getFragmentManager());
            }
        });
        mAdapterHomeInfo.setOnRecommendClickListener(new AdapterHomeInfo.OnRecommendClickListener() {
            @Override
            public void onRecommendClick(HomeRecommendBean bean) {
                String url;
                if (!TextUtils.isEmpty(bean.getMsgLink())) {
                    url = bean.getMsgLink();
                } else {
                    if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                        url = "https://singlepage.storeer.com/v2/SBRecommend?msgCode=" + bean.getMsgCode() + "&token=" + mUserConfigManager.getUserToken();
                    } else {
                        url = "http://192.168.1.102:8088/v2/SBRecommend?msgCode=" + bean.getMsgCode() + "&token=" + mUserConfigManager.getUserToken();
                    }
                }
                EventBus.getDefault().post(new StartBrotherEvent(FragmentRecommendActivity.newInstance(url, bean.getMsgTitle())));
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (curState == AppBarStateChangeListener.State.COLLAPSED) {
                        int firstVisiblePosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
                        if (firstVisiblePosition == 0) {
//                            mAppBarLayout.setExpanded(true, true);
                            //todo 通过alpha值判断expand还是collapse
                        }
                    }
                }
            }
        });
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);

    }

    private void getRecentContact() {
        // 查询最近联系人列表数据
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {

            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable exception) {
                if (code != com.netease.nimlib.sdk.ResponseCode.RES_SUCCESS || recents == null) {
                    return;
                }
                mRecentContacts = recents;
                // 此处如果是界面刚初始化，为了防止界面卡顿，可先在后台把需要显示的用户资料和群组资料在后台加载好，然后再刷新界面
                if (isAdded()) {
                    onRecentContactsLoaded();
                }
            }
        });
    }

    private void getHomeMsgInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        HomeOrderUpdateBean homeOrderUpdateBean = JsonUtil.getGson().fromJson(jsonObject.getString("orderUpdateMsg"), HomeOrderUpdateBean.class);
                        if (homeOrderUpdateBean.getAppMsgCode() != null) {
                            mHomeInfoList.add(0, homeOrderUpdateBean);
                        }
                        JSONArray jsonRobOrders = jsonObject.getJSONArray("orderRobMsg");
                        for (int i = 0; i < jsonRobOrders.length(); i++) {
                            HomeOrderRobBean robBean = JsonUtil.getGson().fromJson(jsonRobOrders.getJSONObject(i).toString(), HomeOrderRobBean.class);
                            robBean.setCount(jsonRobOrders.length());
                            mHomeInfoList.add(robBean);
                        }
                        JSONArray jsonRecommend = jsonObject.getJSONArray("recommendMsg");
                        for (int i = 0; i < jsonRecommend.length(); i++) {
                            HomeRecommendBean recommendBean = JsonUtil.getGson().fromJson(jsonRecommend.getJSONObject(i).toString(), HomeRecommendBean.class);
                            mHomeInfoList.add(recommendBean);
                        }
                        refreshRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodGuide.getHomeMessage(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), this, FragmentEvent.DESTROY_VIEW);
    }

    private void onRecentContactsLoaded() {
        if (mHomeInfoList.size() != 0) {
            ArrayList<MultiItemEntity> list = new ArrayList<>();
            for (MultiItemEntity entity : mHomeInfoList) {
                if (entity instanceof HomeMsgBean) {
                    list.add(entity);
                }
            }
            mHomeInfoList.removeAll(list);
        }
        for (int i = 0; i < mRecentContacts.size(); i++) {
            RecentContact contact = mRecentContacts.get(i);
            if (contact.getUnreadCount() != 0) {
                HomeMsgBean msgBean = new HomeMsgBean();
                msgBean.setAccount(contact.getContactId());
                msgBean.setMessage(contact.getContent());
                msgBean.setName(contact.getFromNick());
                msgBean.setTime(contact.getTime());
                msgBean.setCount(contact.getUnreadCount());
                mHomeInfoList.add(msgBean);
            }
        }
        refreshRecyclerView();
    }

    @Override
    public void onResume() {
        super.onResume();
        mTopPoint[0] += ConvertUtils.dp2px(16);
        if (userBean == null) {
            initRequest();
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (userBean == null) {
            initRequest();
        }
    }

    @Override
    public void onDestroyView() {
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, false);
        incomingMessageObserver = null;
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfoChange(UserInfoChangeEvent event) {
        userBean = event.getUserBean();
        ImageLoaderUtils.displayCircle(mContext, ivGuider, userBean.getStaffHeadPicUrl());
        tvGuiderName.setText(userBean.getStaffNickName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageRead(MessageReadEvent event) {
        ivGuider.postDelayed(new Runnable() {
            @Override
            public void run() {
                getRecentContact();
            }
        }, 200);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeMsgRefresh(HomeOrderRefreshEvent event) {
        if (mHomeInfoList.size() != 0) {
            ArrayList<MultiItemEntity> list = new ArrayList<>();
            for (MultiItemEntity entity : mHomeInfoList) {
                if (entity instanceof HomeOrderUpdateBean || entity instanceof HomeOrderRobBean) {
                    list.add(entity);
                }
            }
            mHomeInfoList.removeAll(list);
        }
        getHomeMsgInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeMiji(HomeMijiEvent event) {
        if (mHomeInfoList.size() != 0) {
            ArrayList<MultiItemEntity> list = new ArrayList<>();
            for (MultiItemEntity entity : mHomeInfoList) {
                if (entity instanceof HomeMijiBean) {
                    list.add(entity);
                }
            }
            mHomeInfoList.removeAll(list);
        }
        String mijiInfo = event.getMijiInfo();
        mUserConfigManager.setMijiInfo(mijiInfo);
        mUserConfigManager.save2Sp(true);
        bindMiji(mijiInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeRecommend(HomeRecommendEvent event) {
        if (mHomeInfoList.size() != 0) {
            ArrayList<MultiItemEntity> list = new ArrayList<>();
            for (MultiItemEntity entity : mHomeInfoList) {
                if (entity instanceof HomeRecommendBean) {
                    list.add(entity);
                }
            }
            mHomeInfoList.removeAll(list);
        }
        getHomeMsgInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshChats(ChangeStaffEvent event) {
        NIMClient.getService(MsgService.class).deleteRecentContact2(event.getAccId(), SessionTypeEnum.P2P);
        ivGuider.postDelayed(new Runnable() {
            @Override
            public void run() {
                getRecentContact();
            }
        }, 200);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshChats(GuideDivideUpdateEvent event) {
        getStaffInfo();
    }

    private void bindMiji(String info) {
        HomeMijiBean mijiBean = JsonUtil.getGson().fromJson(info, HomeMijiBean.class);
        mHomeInfoList.add(mijiBean);
        refreshRecyclerView();
    }

    private void refreshRecyclerView() {
        if (ivGuider != null) {
            sortMsg();
            if (mHomeInfoList.size() != 0) {
                mAdapterHomeInfo.notifyDataSetChanged();
            } else {
                bindEmpty();
            }
            ivGuider.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mRecyclerView.canScrollVertically(1) && mAdapterHomeInfo.getFooterLayoutCount() == 0) {
                        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_end_footer, (ViewGroup) mRecyclerView.getParent(), false);
                        mAdapterHomeInfo.addFooterView(view);
                    }
                    if (!mRecyclerView.canScrollVertically(1) && mAdapterHomeInfo.getFooterLayoutCount() != 0) {
                        mAdapterHomeInfo.removeAllFooterView();
                    }
                }
            }, 200);
        }
    }

    private void setUpRecyclerView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
    }

    private void translationView(float offset) {
        layoutLogos.getLocationOnScreen(mLayoutLogosPoint);
        float yTitleOffset = -(mLayoutLogosPoint[1] - mTopPoint[1]) * offset;
        layoutTop.setAlpha((float) (1 - offset * 1.5));
        ivWave.setAlpha((float) (1 - offset * 1.5));
        ivLine.setAlpha((float) (1 - offset * 1.5));
//      layoutTopContent.setTranslationY(yTitleOffset);
//      LogUtils.d("yTitleOffset============" + yTitleOffset);
        setAnim(tvScanner, offset);
        setAnim(tvProduct, offset);
        setAnim(tvActivity, offset);
        setAnim(tvOrder, offset);
        noDataView.setTranslationY(-yTitleOffset);

//      setAnim(layoutTopContent, offset, yTitleOffset);
        layoutTopContent.setAlpha(1 - offset * 2);

        layoutLogoToolbar.setAlpha(offset);
        checkToolbarIfClick();
    }

    private void setAnim(View view, float offset) {
        view.setAlpha(1 - offset * 6);
        if (view.getAlpha() < 0.6f) {
            view.setClickable(false);
        } else {
            view.setClickable(true);
        }
    }

    private void bindEmpty() {
        mAdapterHomeInfo.setNewData(mHomeInfoList);
        mAdapterHomeInfo.setEmptyView(noDataView);
    }

    private void sortMsg() {
        Collections.sort(mHomeInfoList, new Comparator<MultiItemEntity>() {
            @Override
            public int compare(MultiItemEntity o1, MultiItemEntity o2) {
                long time1 = 0;
                if (o1 instanceof HomeOrderUpdateBean) {
                    time1 = TimeUtils.string2Millis(((HomeOrderUpdateBean) o1).getCreateTime());
                } else if (o1 instanceof HomeOrderRobBean) {
                    time1 = TimeUtils.string2Millis(((HomeOrderRobBean) o1).getCreateTime());
                } else if (o1 instanceof HomeMsgBean) {
                    time1 = ((HomeMsgBean) o1).getTime();
                } else if (o1 instanceof HomeMijiBean) {
                    time1 = TimeUtils.string2Millis(((HomeMijiBean) o1).getCreateTime());
                } else if (o1 instanceof UpdateInfoBean) {
                    time1 = TimeUtils.string2Millis(((UpdateInfoBean) o1).getReleaseTime());
                } else if (o1 instanceof HomeRecommendBean) {
                    time1 = TimeUtils.string2Millis(((HomeRecommendBean) o1).getCreateTime());
                }
                long time2 = 0;
                if (o2 instanceof HomeOrderUpdateBean) {
                    time2 = TimeUtils.string2Millis(((HomeOrderUpdateBean) o2).getCreateTime());
                } else if (o2 instanceof HomeOrderRobBean) {
                    time2 = TimeUtils.string2Millis(((HomeOrderRobBean) o2).getCreateTime());
                } else if (o2 instanceof HomeMsgBean) {
                    time2 = ((HomeMsgBean) o2).getTime();
                } else if (o2 instanceof HomeMijiBean) {
                    time2 = TimeUtils.string2Millis(((HomeMijiBean) o2).getCreateTime());
                } else if (o2 instanceof UpdateInfoBean) {
                    time2 = TimeUtils.string2Millis(((UpdateInfoBean) o2).getReleaseTime());
                } else if (o2 instanceof HomeRecommendBean) {
                    time2 = TimeUtils.string2Millis(((HomeRecommendBean) o2).getCreateTime());
                }
                if (time1 > time2) {
                    return -1;
                } else if (time1 < time2) {
                    return 1;
                }
                return 0;
            }
        });
    }

    @OnClick({R.id.tv_scanner, R.id.iv_scanner})
    void scan() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentCheckout.newInstance()));
    }

    @OnClick({R.id.tv_product, R.id.iv_product})
    void product() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentSelectGoods.newInstance(AppConstant.GOODS_SELECT_IN_MANAGEMENT)));
    }

    @OnClick({R.id.tv_order, R.id.iv_order})
    void order() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentOrderManager.newInstance()));
    }

    @OnClick({R.id.tv_activity, R.id.iv_activity})
    void activity() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentActivityList.newInstance()));
    }

    @OnClick(R.id.iv_barcode)
    void showBarcode() {
        if (userBean != null) {
            DialogShowBarcode dialogShowBarcode = DialogShowBarcode.getDialogShowBarcode(userBean);
            dialogShowBarcode.show(getFragmentManager(), getPageTag());
        }
    }

    @OnClick(R.id.layout_quick_pay)
    void quickPay() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentSureOrder.newInstance()));
    }

    private void checkToolbarIfClick() {
        if (layoutLogoToolbar.getAlpha() < 0.8f) {
            ivScanner.setClickable(false);
            ivProduct.setClickable(false);
            ivOrder.setClickable(false);
            ivActivity.setClickable(false);
        } else {
            ivScanner.setClickable(true);
            ivProduct.setClickable(true);
            ivOrder.setClickable(true);
            ivActivity.setClickable(true);
        }
    }

    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
            if (ivGuider != null) {
                ivGuider.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getRecentContact();
                    }
                }, 200);
            }
        }
    };
}
